<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="viewport" content="width=device-width, initial-scale=1.0">
    <meta charset="UTF-8">
    <title>需求发布平台</title>
    <link rel="stylesheet" href="publisher/css/base/reset.css">
    <link rel="stylesheet" href="publisher/css/components/navbar.css">
    <link rel="stylesheet" href="publisher/css/components/editor.css">
    <link rel="stylesheet" href="publisher/css/components/maintenance.css">
    <link rel="stylesheet" href="publisher/css/components/messages.css">
    <link rel="stylesheet" href="publisher/css/main.css">
</head>
<body>
    <nav class="navbar">
        <div class="nav-left">
            <div class="nav-item active">新建需求</div>
            <div class="nav-item">需求维护池</div>
            <div class="nav-item">消息</div>
        </div>
        <div class="user-info">
            <span>张三</span>
            <div class="avatar"></div>
            <div class="user-dropdown">
                <div>手机号/邮箱：
                    <span id="user-contact">已登录的手机号或邮箱</span>
                </div>
                <div class="upload-avatar">
                    <img src="publisher/assets/images/avatar-placeholder.png" alt="头像">
                    <a href="#" id="upload-avatar-link">上传/修改头像</a>
                </div>
                <button id="change-password-btn">修改密码</button>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="top-section">   
            <div class="mind-map">
                <h3 style="margin-bottom: 12px; color: #333;">需求脑图</h3>
                <div style="height: calc(100% - 40px); border: 1px dashed #ddd;
                     border-radius: 4px; display: grid; place-items: center;
                     color: #999;">
                    脑图区域（可集成专业脑图库）
                </div>
            </div>
            
            <div class="description">
                <h3 style="margin-bottom: 12px; color: #333;">需求描述</h3>
                <textarea id="demand-description" placeholder="请输入详细的需求描述..."></textarea>
            </div>
        </div>
        <div class="bottom-section">
            <textarea class="input-demand" id="input-demand" placeholder="输入您的需求内容...（支持Markdown格式）"></textarea>
            <button class="confirmsub-btn" id="confirmsub-btn">⬆️ 确定需求</button>
            <button class="upload-btn">
                <span>📎 上传附件</span>
                <input type="file" hidden multiple>
            </button>
        </div>
        <div class="middle-area">
            <button class="create-btn">创建新需求</button>
        </div>
    </div>

    <div class="maintenance-container">
        <div class="left-nav">
            <div class="dropdown main-demand-dropdown">
                选择已发布的需求
                <div class="dropdown-content">
                    <div data-demand-id="1">主需求一</div>
                    <div data-demand-id="2">主需求二</div>
                </div>
            </div>
            <div class="dropdown sub-demand-dropdown">
                 下拉选择子需求
                <div class="dropdown-content">
                    <div>子需求一</div>
                    <div>子需求二</div>
                </div>
            </div>
            <div class="option" id="overview-option">概览</div>
            <div class="option" id="sub-demand-option">子需求</div>
        </div>
        <div class="right-content">
            <div class="overview">
                <h3 style="margin-bottom: 12px; color: #333;">子需求名称/某需求的概览：</h3>
            </div>

            <div class="horizontal-layout">
                <div class="mind-map">
                    <h3 style="margin-bottom: 12px; color: #333;">需求脑图</h3>
                    <div style="height: calc(100% - 40px); border: 1px dashed #ddd;
                         border-radius: 4px; display: grid; place-items: center;
                         color: #999;">
                        脑图区域（可集成专业脑图库）
                    </div>
                </div>
                
                <div class="description">
                    <h3 style="margin-bottom: 12px; color: #333;">需求描述</h3>
                    <textarea placeholder="请输入详细的需求描述..."></textarea>
                </div>
            </div>

            <div class="history-section">
                <h3 style="margin-bottom: 12px; color: #333;">历史修改：</h3>
                <div class="history-item">
                    <div class="content">某人修改：</div>
                    <div class="content">原内容：<br>...</div>
                    <div class="content">修改为：<br>...</div>
                </div>
            </div>

            <button class="save-btn">保存</button>
        </div>
    </div>

       <!-- 消息容器 -->
    <div class="messages-container" style="display: none;">
        <div class="left-nav">
            <div class="demand-item active">需求一（名称）</div>
            <div class="demand-item">需求二</div>
        </div>
        <div class="right-content">
            <div class="demand-details">
                <div class="demand-name">需求名称：需求一（名称）</div>
                <div class="user-name">用户名称：用户11111</div>
                <div class="reply">回复：这里是专家的回复内容...</div>
                <button class="reply-btn">点击回复</button>
                <div class="reply-box">
                    <textarea class="reply-textarea" placeholder="请输入您的回复内容..."></textarea>
                    <button class="confirm-btn">确认</button>
                </div>
            </div>
            <div class="message-list">
                <!-- 评论和回复区分展示 -->
                <div class="message-item comment">
                    <div class="sender">用户11111</div>
                    <div class="content">请问这个需求什么时候可以完成？我比较着急。</div>
                    <div class="time">2023-05-20 10:30</div>
                </div>
                <div class="message-item reply-message">
                    <div class="sender">我的回复：</div>
                    <div class="content">您好，这个需求我们正在处理中，预计下周可以完成。</div>
                    <div class="time">2023-05-20 11:15</div>
                </div>
                <div class="message-item comment">
                    <div class="sender">用户11111</div>
                    <div class="content">好的，谢谢，希望能按时完成。</div>
                    <div class="time">2023-05-20 14:20</div>
                </div>
                <div class="message-item reply-message">
                    <div class="sender">我的回复：</div>
                    <div class="content">我们会尽快处理，请您放心。</div>
                    <div class="time">2023-05-20 15:30</div>
                </div>
            </div>
        </div>
    </div>

    <!-- 修改密码界面 -->
    <div class="change-password-container" style="display: none;">
        <div class="change-password-form">
            <div>
                <label for="user-contact-display">手机号/邮箱</label>
                <input type="text" id="user-contact-display" disabled value="已登录的手机号或邮箱">
            </div>
            <div class="verification-container">
                <input type="text" id="verification-code" placeholder="验证码">
                <button id="get-verification-code">获取</button>
            </div>
            <div>
                <input type="password" id="new-password" placeholder="新密码">
            </div>
            <div>
                <input type="password" id="confirm-password" placeholder="确认新密码">
            </div>
            <div>
                <button id="confirm-change-password">确认修改</button>
            </div>
            <div>
                <button id="return-to-user-info">返回</button>
            </div>
        </div>
    </div>

    <!-- 上传头像表单 -->
    <form id="avatar-upload-form" style="display: none;">
        <input type="file" id="avatar-upload" accept="image/*">
    </form>

    <script src="publisher/js/app.js"></script>
    
    <!-- 添加需求发送功能的脚本 -->
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const inputDemand = document.getElementById('input-demand');
        const confirmSubBtn = document.getElementById('confirmsub-btn');
        const demandDescription = document.getElementById('demand-description');
        
        let isWaitingForResponse = false;
        let conversationId = "";
        
        // 显示加载指示器
        function showLoadingIndicator() {
            // 在需求描述区域显示加载中提示
            demandDescription.value = "正在生成需求描述，请稍候...";
            demandDescription.disabled = true;
        }
        
        // 移除加载指示器
        function removeLoadingIndicator() {
            demandDescription.disabled = false;
        }
        
        // 发送需求到服务器
        async function sendDemand(demand) {
            try {
                // 显示加载指示器
                showLoadingIndicator();
                
                // 准备请求数据
                const requestData = {
                    query: demand,
                    user: "publisher-user-" + Date.now(),
                    inputs: {},
                    response_mode: "streaming",
                    conversation_id: conversationId
                };
                
                // 发送请求
                const response = await fetch('/api/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                // 处理流式响应
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let buffer = '';
                let finalAnswer = '';
                
                while (true) {
                    const { value, done } = await reader.read();
                    if (done) break;
                    
                    buffer += decoder.decode(value, { stream: true });
                    
                    // 处理缓冲区中的每一行
                    while (buffer.includes('\n')) {
                        const lineEnd = buffer.indexOf('\n');
                        const line = buffer.slice(0, lineEnd).trim();
                        buffer = buffer.slice(lineEnd + 1);
                        
                        if (line.startsWith('data:')) {
                            try {
                                const jsonData = JSON.parse(line.slice(5).trim());
                                
                                // 更新会话ID
                                if (jsonData.conversation_id) {
                                    conversationId = jsonData.conversation_id;
                                }
                                
                                // 更新响应内容
                                if (jsonData.answer) {
                                    finalAnswer = jsonData.answer;
                                    demandDescription.value = finalAnswer;
                                }
                            } catch (e) {
                                console.error('解析JSON失败:', e, line);
                            }
                        }
                    }
                }
                
                // 处理剩余的缓冲区
                if (buffer.trim() && buffer.trim().startsWith('data:')) {
                    try {
                        const jsonData = JSON.parse(buffer.trim().slice(5).trim());
                        if (jsonData.answer) {
                            finalAnswer = jsonData.answer;
                            demandDescription.value = finalAnswer;
                        }
                    } catch (e) {
                        console.error('解析最终JSON失败:', e, buffer);
                    }
                }
                
                // 确保最终答案显示在需求描述区域
                demandDescription.value = finalAnswer || "无法生成需求描述，请重试";
                
            } catch (error) {
                console.error('发送需求错误:', error);
                demandDescription.value = `发送需求失败: ${error.message}`;
            } finally {
                isWaitingForResponse = false;
                inputDemand.disabled = false;
                confirmSubBtn.disabled = false;
                removeLoadingIndicator();
            }
        }
        
        // 确定需求按钮点击事件
        confirmSubBtn.addEventListener('click', function() {
            const demand = inputDemand.value.trim();
            if (demand && !isWaitingForResponse) {
                isWaitingForResponse = true;
                inputDemand.disabled = true;
                confirmSubBtn.disabled = true;
                
                sendDemand(demand);
            }
        });
        
        // 输入框回车事件
        inputDemand.addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && e.ctrlKey && inputDemand.value.trim() && !isWaitingForResponse) {
                e.preventDefault();
                confirmSubBtn.click();
            }
        });
    });
    </script>
</body>
</html>